package com.lijunjie.platform.api.commons;


import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ShiroException.class)
    public Object handleShiroException(ShiroException e) {
        BaseResponse<Object> ret = new BaseResponse<>();
        ret.setCode(HttpStatus.UNAUTHORIZED.value());
        ret.setMsg(e.getMessage());
        return ret;
    }

    @ExceptionHandler(IncorrectCredentialsException.class)
    public Object handleIncorrectCredentialsException() {
        BaseResponse<Object> ret = new BaseResponse<>();
        ret.setCode(HttpStatus.UNAUTHORIZED.value());
        ret.setMsg("密码错误！");
        return ret;
    }

    @ExceptionHandler(UnknownAccountException.class)
    public Object handleUnknownAccountException() {
        BaseResponse<Object> ret = new BaseResponse<>();
        ret.setCode(HttpStatus.UNAUTHORIZED.value());
        ret.setMsg("用户名不存在！");
        return ret;
    }

    @ExceptionHandler(LockedAccountException.class)
    public Object handleLockedAccountException() {
        BaseResponse<Object> ret = new BaseResponse<>();
        ret.setCode(HttpStatus.UNAUTHORIZED.value());
        ret.setMsg("账户已被锁定！");
        return ret;
    }

    @ExceptionHandler(UnauthorizedException.class)
    public Object handleUnauthorizedException() {
        BaseResponse<Object> ret = new BaseResponse<>();
        ret.setCode(HttpStatus.UNAUTHORIZED.value());
        ret.setMsg("权限不足！");
        return ret;
    }

    @ExceptionHandler(UnauthenticatedException.class)
    public Object handleUnauthenticatedException() {
        BaseResponse<Object> ret = new BaseResponse<>();
        ret.setCode(HttpStatus.UNAUTHORIZED.value());
        ret.setMsg("认证失败！");
        return ret;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Object handleDuplicateKeyException(){
        BaseResponse<Object> response = new BaseResponse<>();
        response.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setMsg("违反唯一约束条件");
        return response;
    }

    @ExceptionHandler(Exception.class)
    public Object globalException(Exception e) {
        BaseResponse<Object> ret = new BaseResponse<>();
        ret.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        ret.setMsg(e.getMessage());
        return ret;
    }

}